const express = require('express');
const router = express.Router();
const { Article, User } = require('../models');
const { success, failure } = require('../utils/responses');
const { NotFoundError } = require("../utils/errors");

/**
 * 查询文章列表
 * GET /articles
 */
router.get('/', async function (req, res) {
    try {
        const query = req.query;
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        const offset = (currentPage - 1) * pageSize;

        const condition = {
            attributes: { exclude: ['content'] },
            order: [['id', 'DESC']],
            limit: pageSize,
            offset: offset,
            where: {},
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['id', 'username', 'nickname', 'avatar', 'company'],
                }
            ]
        };

        if (query.userId) {
            condition.where.userId = query.userId;
        }

        const { count, rows } = await Article.findAndCountAll(condition);
        success(res, '查询文章列表成功。', {
            articles: rows,
            pagination: {
                total: count,
                currentPage,
                pageSize,
            }
        });
    } catch (error) {
        failure(res, error);
    }
});

/**
 * 查询文章详情
 * GET /articles/:id
 */
router.get('/:id', async function (req, res) {
    try {
        const { id } = req.params;

        const condition = {
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['id', 'username', 'nickname', 'avatar', 'company'],
                }
            ]
        }
        const article = await Article.findByPk(id, condition);
        if (!article) {
            throw new NotFoundError(`ID: ${id}的文章未找到。`)
        }

        success(res, '查询文章成功。', { article });
    } catch (error) {
        failure(res, error);
    }
});

//创建文章
router.post("/", async function (req, res) {
    try {
        //白名单过滤
        const body = filterBody(req);
        const article = await Article.create(body);

        success(res, "创建文章成功", { article }, 201);
    } catch (error) {
        failure(res, error);
    }
});

//删除文章
/**
 * 删除文章
 * DELETE /articles/:id
 */
router.delete("/:id", async function (req, res) {
    try {
        const { id } = req.params;
        const userId = req.userId;

        // 查找文章并检查是否属于当前用户
        const article = await Article.findOne({
            where: { id, userId },
        });

        if (!article) {
            return failure(res, { message: "文章不存在或无权删除" }, 403);
        }

        await article.destroy();
        success(res, "删除文章成功");
    } catch (error) {
        failure(res, error);
    }
});

function filterBody(req) {
    return {
        title: req.body.title,
        content: req.body.content,
        userId: req.body.userId,
    };
}

module.exports = router;
